package com.adulcimer.controllers;

import cn.dev33.satoken.annotation.SaIgnore;
import com.adulcimer.models.dto.WordTagDto;
import com.adulcimer.services.PoiService;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * @Classname Simon
 * @Description
 * @Date 2025/3/11 14:23
 * @Created by Simon
 */
@RestController
@RequestMapping("/api/poi")
@Tag(name = "poi", description = "poi接口")
public class PoiController {
    @Resource
    private PoiService poiTestService;

    /**
     * 上传模板文件并解析所有占位符标签（包括段落、表格）
     */
    @PostMapping(value = "/parse", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @SaIgnore
    public List<WordTagDto> parseTemplate(@RequestParam("file") MultipartFile file) throws Exception {
        InputStream templateStream = file.getInputStream();
        return poiTestService.parseTemplate(templateStream);
    }

    /**
     * 根据前端传回的数据填充模板，生成最终文档
     * 假设前端传入 dataMap 的 key 与占位符内部一致，例如 "table.string.name"
     */
    @PostMapping("/fill")
    @SaIgnore
    public void fillTemplate(@RequestParam("templateFile") MultipartFile file,
                             @RequestBody Map<String, String> dataMap,
                             HttpServletResponse response) throws Exception {
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        // 设置下载文件名
        response.setHeader("Content-Disposition", "attachment; filename=generated.docx");
        InputStream templateStream = file.getInputStream();
        poiTestService.fillTemplate(templateStream, dataMap, response.getOutputStream());
    }
}
